package cn.wildfire.chat.kit.group;

import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.wildfire.chat.app.extendsion.classes.GroupMembersByApiRequest;
import cn.wildfire.chat.app.extendsion.ui.SmoothToggleAndSlideAnimationForUI;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.kit.contact.model.UIUserInfo;
import cn.wildfire.chat.kit.group.manage.OnPickUserStatusChangeListener;
import cn.wildfire.chat.kit.third.utils.UIUtils;
import cn.wildfirechat.model.GroupMember;
import cn.wildfirechat.remote.ChatManager;

public class RemoveGroupMemberActivity extends BasePickGroupMemberActivity {

    private MenuItem menuItem;
    public static final int RESULT_REMOVE_SUCCESS = 2;
    public static final int RESULT_REMOVE_FAIL = 3;
    private GroupViewModel groupViewModel;
    private List<UIUserInfo> checkedGroupMembers;

    @Override
    protected void onGroupMemberChecked(List<UIUserInfo> checkedUserInfos) {
        this.checkedGroupMembers = checkedUserInfos;
        if (checkedUserInfos == null || checkedUserInfos.isEmpty()) {
            menuItem.setTitle("删除");
            menuItem.setEnabled(false);
        } else {
            menuItem.setTitle("删除(" + checkedUserInfos.size() + ")");
            menuItem.setEnabled(true);
        }
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
        GroupMember groupMember = groupViewModel.getGroupMember(groupInfo.target, ChatManager.Instance().getUserId());
        if (groupMember.type == GroupMember.GroupMemberType.Manager) {
            pickUserViewModel.addUncheckableIds(Collections.singletonList(groupInfo.owner));
        }
        new GroupMembersByApiRequest(this, groupInfo.target, new GroupMembersByApiRequest.OnGetGroupMembersListener() {
            @Override
            public void result(List<GroupMember> groupMemberList) {
                if (groupMemberList == null || groupMemberList.isEmpty()) {
                    Toast.makeText(RemoveGroupMemberActivity.this, "get groupMembers error", Toast.LENGTH_SHORT).show();
                    return;
                }
                GroupMember owner = null;
                List<String> managerMemberIds = new ArrayList<>();
                List<String> memberIds = new ArrayList<>();
                for (GroupMember member : groupMemberList) {
                    if (member.type == GroupMember.GroupMemberType.Manager) {
                        managerMemberIds.add(member.memberId);
                    } else if (member.type == GroupMember.GroupMemberType.Owner) {
                        owner = member;
                    }
                }
                String userId = ChatManager.Instance().getUserId();
                if (owner != null && owner.memberId.equals(userId)) {
                    memberIds.add(owner.memberId);
                } else {
                    memberIds.add(owner.memberId);
                    memberIds.addAll(managerMemberIds);
                }
                pickUserViewModel.setUncheckableIds(memberIds);
                pickGroupMemberFragment.getUsersRecyclerView().getAdapter().notifyDataSetChanged();
            }
        });
    }

    @Override
    protected int menu() {
        return R.menu.group_remove_member;
    }

    @Override
    protected void afterMenus(Menu menu) {
        menuItem = menu.findItem(R2.id.remove);
        menuItem.setEnabled(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R2.id.remove) {
            removeMember(checkedGroupMembers);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    void removeMember(List<UIUserInfo> checkedUsers) {
        if (checkedUsers == null || checkedUsers.size() == 0) {
            ToastTip.tip("未选中可删除对象!");
            return;
        }
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("删除中...")
                .progress(true, 100)
                .cancelable(false)
                .build();
        dialog.show();
        if (checkedUsers != null && !checkedUsers.isEmpty()) {
            ArrayList<String> checkedIds = new ArrayList<>(checkedUsers.size());
            for (UIUserInfo user : checkedUsers) {
                checkedIds.add(user.getUserInfo().uid);
            }
            groupViewModel.removeGroupMember(groupInfo, checkedIds).observe(this, result -> {
                dialog.dismiss();
                if (result) {
                    Intent intent = new Intent();
                    intent.putStringArrayListExtra("memberIds", checkedIds);
                    setResult(RESULT_REMOVE_SUCCESS, intent);
                    UIUtils.showToast(UIUtils.getString(R.string.del_member_success));
                } else {
                    setResult(RESULT_REMOVE_FAIL);
                    UIUtils.showToast(UIUtils.getString(R.string.del_member_fail));
                }
                finish();
            });

        }
    }

    /**
     * modify by HEKE , 2019/9/4 18:55 TODO 测试滑动隐藏或显示搜索栏 HEKE_SEARCHLAYOUT_REMOVE
     */
    protected SmoothToggleAndSlideAnimationForUI smoothToggleAndSlideAnimationForUI;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (smoothToggleAndSlideAnimationForUI == null) {
                smoothToggleAndSlideAnimationForUI = new SmoothToggleAndSlideAnimationForUI(this, SmoothToggleAndSlideAnimationForUI.FLAG_GROUP_ADD_REMOVE);
                smoothToggleAndSlideAnimationForUI.setToggleView(pickGroupMemberFragment.getSearchLayout());
                smoothToggleAndSlideAnimationForUI.setSlideView(pickGroupMemberFragment.getUsersRecyclerView(), 0);
            }
            smoothToggleAndSlideAnimationForUI.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 2);
        setReplaceTitle(getTitle().toString(), -1);
        setSearchLayoutVisibility(false);
        setTextThenBinClickForRightTextView(View.VISIBLE, getString(R.string.delete_title), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = getRightTxtView().getText().toString();
                if (text.equals(getString(R.string.delete_title))) {
                    removeMember(checkedGroupMembers);
                } else {
                    // 隐藏搜索内容
                    pickGroupMemberFragment.hideSearchContactFragment();
                }
            }
        });
        pickGroupMemberFragment.setOnPickUserStatusChangeListener(onPickUserStatusChangeListener);
    }

    /**
     * 控制右上角文字变化，搜索显示与取消状态监听
     */
    private OnPickUserStatusChangeListener onPickUserStatusChangeListener = new OnPickUserStatusChangeListener() {
        @Override
        public void showSearchResult(boolean searching) {
            getRightTxtView().setText(searching ? getString(R.string.done_title) : getString(R.string.delete_title));
        }
    };

}
